package net.xumf.support.converter;

import com.google.common.collect.Lists;
import net.xumf.support.model.dto.PageDTO;
import net.xumf.support.model.vo.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 页面模型转换类
 */
public final class PageConverter {

    /**
     * {@link Page} 转 {@link PageVO}
     *
     * @param page {@link Page}
     * @return {@link PageVO}
     */
    public static PageVO pageToPageDTO(final Page page) {

        return PageVO.builder()
                .total(page.getTotalPages())
                .page(page.getNumber() + 1)
                .records(page.getTotalElements())
                .rows(page.getContent())
                .build();
    }

    /**
     * {@link PageDTO} 转 {@link Pageable}
     *
     * @param pageDTO {@link PageDTO}
     * @return {@link Pageable}
     */
    public static Pageable pageVOToPageable(PageDTO pageDTO) {
        if (StringUtils.isEmpty(pageDTO.getOrders())) {
            return PageRequest.of(pageDTO.getPage() - 1, pageDTO.getRows());
        } else {
            String[] directions = pageDTO.getDirections().split(",");
            List<Sort.Order> orders = new ArrayList<>();
            ArrayList<String> orderProperties = Lists.newArrayList(pageDTO.getOrders().split(","));
            for (int i = 0; i < orderProperties.size(); i++) {
                String op = orderProperties.get(i);
                if (i < directions.length) {
                    Sort.Direction direction = "descending".equals(directions[i]) ? Sort.Direction.DESC : Sort.Direction.ASC;
                    orders.add(new Sort.Order(direction, op));
                }
            }
            return PageRequest.of(pageDTO.getPage() - 1, pageDTO.getRows(), Sort.by(orders));
        }
    }
}
